package com.itlong.cloud.rabbitmq.consumer;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.property.AppUserDelInvitedAuthDTO;
import com.itlong.cloud.POJO.DTO.property.HouseHoldManageJPushDTO;
import com.itlong.cloud.POJO.DTO.property.UserDeviceAuthAddreddDTO;
import com.itlong.cloud.POJO.PO.TimeTaskDeadMessageQueuePO;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.enumerate.HouseHoldJPushSceneTypeEnum;
import com.itlong.cloud.property.service.IPropertyDeviceAuthService;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import com.rabbitmq.client.Channel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;


/**
 * <desc>
 *      住户设备权限业务操作队列消费者
 * </desc>
 *
 * @createDate 2017-11-08
 */
@Component
public class HouserHoldDeviceAuthConsumer {
    private static final Logger LOG = LoggerFactory.getLogger(HouserHoldDeviceAuthConsumer.class);

    @Autowired
    IPropertyDeviceAuthService iPropertyDeviceAuthService;

    @Autowired
    private MessageSender messageSender;

    /**
     * <desc>
     *      用户设备权限业务操作队列消费者
     * </desc>
     * @param message 消息
     * @param channel
     * @return
     * @author zhangs
     * @createDate 2017/11/6
     */
    @RabbitListener(queues = RabbitMQConstant.RABBITMQ_USER_SAVE_DEVICE_AUTH_INFO_QUEUE)
    public void process(Message message, Channel channel) throws InterruptedException, IOException {
        byte[] body = message.getBody();
        //LOG.info("RabbitMQ_用户设备权限业务消费端:"+body);
        try {
            TimeTaskDeadMessageQueuePO timeTaskDeadMessageQueuePO = JSON.parseObject(new String(body), TimeTaskDeadMessageQueuePO.class);
            JSONObject dataJs = JSON.parseObject(timeTaskDeadMessageQueuePO.getMessageContent());
            JSONObject dataContent = dataJs.getJSONObject("data");
            JSONArray userDeviceAuthAddreddDTOSArr = dataContent.getJSONArray("userDeviceAuthAddreddDTOS");
            //住户最新有权限地址集
            List<UserDeviceAuthAddreddDTO> userDeviceAuthAddreddDTOS =
                    JSON.parseArray(userDeviceAuthAddreddDTOSArr.toJSONString(), UserDeviceAuthAddreddDTO.class);
            //住户权限来源标识
            Integer authSource = dataContent.getInteger("authSource");
            //极光推送场景
            String sceneType = dataContent.getString("sceneType");
            //需额外删除 被邀请而被赋予权限 的二级用户
            JSONObject delInvitedAuthDTOMapJs = dataContent.getJSONObject("delInvitedAuthDTOMap");
            Map<String, AppUserDelInvitedAuthDTO> delInvitedAuthDTOMap = new HashMap<>();
            if ((userDeviceAuthAddreddDTOS != null && !userDeviceAuthAddreddDTOS.isEmpty()) && (authSource != null)) {
                Map<String, Object> delInvitedAuthDTOTempMap;
                for (UserDeviceAuthAddreddDTO userDeviceAuthAddreddDTO:userDeviceAuthAddreddDTOS) {
                    if (delInvitedAuthDTOMapJs != null) {
                        delInvitedAuthDTOTempMap = JSON.parseObject(delInvitedAuthDTOMapJs.toJSONString());
                        String userId = userDeviceAuthAddreddDTO.getUserId();
                        Map<String, String> userIdMap = JSON.parseObject(JSON.toJSONString(delInvitedAuthDTOTempMap.get(userId)), HashMap.class);
                        if (userIdMap != null) {
                            AppUserDelInvitedAuthDTO appUserDelInvitedAuthDTO = new AppUserDelInvitedAuthDTO(userIdMap.get("userId"), userIdMap.get("parentUserId"));
                            /*AppUserDelInvitedAuthDTO appUserDelInvitedAuthDTO = JSON.parseObject((String) delInvitedAuthDTOTempMap.get(userId),
                                    AppUserDelInvitedAuthDTO.class);*/
                            delInvitedAuthDTOMap.put(userId, appUserDelInvitedAuthDTO);
                        }
                    }
                    //住户地址全迁时userAuthRoomAddrMap为空
                    Map<String, Object> userAuthRoomAddrMap = userDeviceAuthAddreddDTO.getUserAuthRoomAddrMap();
                    if (userAuthRoomAddrMap != null) {
                        Set<String> buildIdSet = userAuthRoomAddrMap.keySet();
                        for (String buildId : buildIdSet) {
                            Map<String, String> unitMap = JSON.parseObject(JSON.toJSONString(userAuthRoomAddrMap.get(buildId)), HashMap.class);
                            userAuthRoomAddrMap.put(buildId, unitMap);
                        }
                    }
                }

//                    iPropertyDeviceAuthService.saveUserAuthByAddr(userDeviceAuthAddreddDTOS, authSource);
//                iPropertyDeviceAuthService.classifyUserDeviceAuth(delInvitedAuthDTOMap,userDeviceAuthAddreddDTOS, authSource);
                List<HouseHoldManageJPushDTO> houseHoldManageJPushDTOS = new ArrayList<>();
                String jPushMessage;
                //物业住户 迁入/迁出/、审核(通过/未通过)时需要极光推送
                if (StringUtils.isBlank(sceneType)) {
                    jPushMessage = null;
                } else {
                    //推送指令
                    Map<String,String> comands = new HashMap<>();
                    comands.put("refreshSips", "1");
                    for (UserDeviceAuthAddreddDTO userDeviceAuthAddreddDTO:userDeviceAuthAddreddDTOS) {
                        String projectId = userDeviceAuthAddreddDTO.getProjectId();
                        String phoneNum = userDeviceAuthAddreddDTO.getPhoneNum();
                        String jPushMsg = userDeviceAuthAddreddDTO.getJpushMsg();
                        //判断推送场景类型，拼接极光推送消息
                        String msg = "";
                        if (StringHandlerUtil.compareStrWithOutEmpty(
                                HouseHoldJPushSceneTypeEnum.HOUSEHOLD_J_PUSH_SCENE_TYPE_MOVE_IN.getType(), sceneType)) {
                            //迁入
                            msg = "您已被迁入到{" + jPushMsg + "}房间...";
                        } else if (StringHandlerUtil.compareStrWithOutEmpty(
                                HouseHoldJPushSceneTypeEnum.HOUSEHOLD_J_PUSH_SCENE_TYPE_MOVE_OUT.getType(), sceneType)) {
                            //迁出
                            msg = "您已从{" + jPushMsg + "}房间被迁出...";
                        } else if (StringHandlerUtil.compareStrWithOutEmpty(
                                HouseHoldJPushSceneTypeEnum.HOUSEHOLD_J_PUSH_SCENE_TYPE_PASS.getType(), sceneType)) {
                            //审核通过
                            msg = "您{" + jPushMsg + "}房间的权限审核已通过";
                        } else if (StringHandlerUtil.compareStrWithOutEmpty(
                                HouseHoldJPushSceneTypeEnum.HOUSEHOLD_J_PUSH_SCENE_TYPE_NOT_PASS.getType(), sceneType)) {
                            //审核未通过
                            msg = "您{" + jPushMsg + "}房间的权限审核未通过";
                            //审核未通过无需App端刷新只需提示
                            comands.put("refreshSips", "2");
                        }

                        HouseHoldManageJPushDTO houseHoldManageJPushDTO = new HouseHoldManageJPushDTO();
                        houseHoldManageJPushDTO.setComands(comands);
                        houseHoldManageJPushDTO.setProjectId(projectId);
                        houseHoldManageJPushDTO.setPhoneNum(phoneNum);
                        houseHoldManageJPushDTO.setMsg(msg);
                        houseHoldManageJPushDTOS.add(houseHoldManageJPushDTO);
                    }
                    jPushMessage = JSON.toJSONString(houseHoldManageJPushDTOS);
                }
                iPropertyDeviceAuthService.classifyUserDeviceAuth(
                        delInvitedAuthDTOMap,userDeviceAuthAddreddDTOS, authSource, jPushMessage);
            }
        } catch (Exception e) {
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            LOG.error("【RabbitMQ_住户设备权限业务消费端】:解析异常",e);
        } finally {
            //手动确认消息消费成功。
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}
